﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;

namespace System.Modules.Extensions
{
    /// <summary>
    /// Query String Extensions
    /// </summary>
    public static class QueryStringExtensions
    {
        #region CleanQueryString
        /// <summary>
        /// This method removes array of parameters from the query string 
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="parametersToRemove"></param>
        /// <returns>
        /// it returns a new query string with the parameters removed.
        /// </returns>
        public static string CleanQueryString(this NameValueCollection queryString, params string[] parametersToRemove)
        {
            var query = new StringBuilder();
            foreach (var queryStringParam in parametersToRemove.SelectMany(remove => queryString.Cast<string>().Where(queryStringParam => !queryStringParam.Equals(remove, StringComparison.CurrentCulture))))
            {
                if (query.Length > 0)
                {
                    query.Append("&");
                }
                query.Append(string.Format(CultureInfo.CurrentCulture, "{0}={1}", queryStringParam, queryString[queryStringParam]));
            }

            return query.ToString();
        }
        #endregion

        #region SetQueryStringParameter
        /// <summary>
        /// This method appends a list of parameters to the query string.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="parametersToSet"></param>
        /// <returns>
        /// New Query string with the list of parameters.
        /// </returns>
        public static string SetQueryStringParameter(this NameValueCollection queryString, params KeyValuePair<string, string>[] parametersToSet)
        {
            var query = new StringBuilder();
            foreach (var parameterToSet in parametersToSet)
            {
                foreach (string queryStringParam in queryString)
                {
                    if (query.Length > 0) { query.Append("&"); }
                    if (!queryStringParam.Equals(parameterToSet.Key, StringComparison.CurrentCulture))
                    {
                        query.Append(string.Format(CultureInfo.CurrentCulture, "{0}={1}", queryStringParam, queryString[queryStringParam]));
                    }
                }
                if (query.Length > 0) { query.Append("&"); }
                query.Append(string.Format(CultureInfo.CurrentCulture, "{0}={1}", parameterToSet.Key, parameterToSet.Value));
            }

            return query.ToString();
        }
        #endregion

    }
}
